﻿// ———————————————————————–
// <copyright file="KeywordRoutingService.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// KeywordRoutingService.cs - "Routes The DE Messages Based On Content. "
// Project: "IC.NETSOA"- "KeywordRoutingService"
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2010
// Author:      Don McGarry The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Xml.Linq;
using EDXLSharp;
using EDXLSharp.EDXLDELib;
using ICNETDAL;
using ICNETServices;

namespace KeywordRoutingSvc
{
  /// <summary>
  /// Routes a DE message based on its content. 
  /// </summary>
  public class KeywordRoutingService : IRoutingICNET
  {
    /// <summary>
    /// Examines the categories contained in the DE messages to determine where it should be routed. 
    /// </summary>
    /// <param name="distributionElement">The DE object to be processed.</param>
    [OperationBehavior(TransactionAutoComplete = true)]
    public void ProcessDE(EDXLDE distributionElement)
    {
      try
      {
        List<ValueList> templist;
        bool found;
        if (distributionElement.DistributionType != TypeValue.Cancel)
        {
          foreach (ContentObject co in distributionElement.ContentObjects)
          {
            templist = RouterRulesDAL.GetRoutingDestinations("ContentKeyword", (List<ValueList>) co.ContentKeyword);
            if (co.ConsumerRole.Count == 0)
            {
              foreach (ValueList list in templist)
              {
                list.ValueListURN = list.ValueListURN.Replace("http", "icnet-http");
              }
              co.ConsumerRole = templist;
            }
            else
            {
              foreach (ValueList list in templist)
              {
                found = false;
                foreach (ValueList colist in co.ConsumerRole)
                {
                  if (colist.ValueListURN == list.ValueListURN)
                  {
                    foreach (string val in list.Value)
                    {
                      colist.Value.Add(val);
                    }

                    found = true;
                    break;
                  }
                }

                if (!found)
                {
                  //change the routing url scheme so we can remove this consumer role before caching this DE
                  list.ValueListURN = list.ValueListURN.Replace("http", "icnet-http");

                  co.ConsumerRole.Add(list);
                }
              }
            }
          }
        }

        ValueList servicerole = new ValueList();
        servicerole.ValueListURN = ICNETSOAConstants.ICNETServicesURI;
        servicerole.Value.Add(ICNETSOAConstants.KeywordRoutingServiceNamespace);
        if (distributionElement.SenderRole.Count == 0)
        {
          distributionElement.SenderRole.Add(servicerole);
        }
        else
        {
          found = false;
          foreach (ValueList list in distributionElement.SenderRole)
          {
            if (list.ValueListURN == ICNETSOAConstants.ICNETServicesURI)
            {
              list.Value.Clear();
              list.Value.Add(ICNETSOAConstants.KeywordRoutingServiceNamespace);
              found = true;
              break;
            }
          }

          if (!found)
          {
            distributionElement.SenderRole.Add(servicerole);
          }
        }

        RouterClient client = new RouterClient();
        client.ProcessDE(distributionElement);
      }
      catch (Exception e)
      {
        ValueList servicerole = new ValueList();
        servicerole.ValueListURN = ICNETSOAConstants.ICNETServicesURI;
        servicerole.Value.Add(ICNETSOAConstants.ExceptionServiceNamespace);
        XNamespace ns = "http://tempuri.org";
        XElement xe = new XElement(ns + "Exception");
        xe.Add(new XElement("Message", e.Message));
        xe.Add(new XElement("StackTrace", e.StackTrace));
        xe.Add(new XElement("ErrorString", e.ToString()));
        ContentObject co = new ContentObject(ICNETSOAConstants.ICNETExceptionURI, new List<string>() { "Exception" });
        co.XMLContent = new XMLContentType();
        co.XMLContent.EmbeddedXMLContent.Add(xe);
        distributionElement.ContentObjects.Add(co);
        if (distributionElement.SenderRole.Count == 0)
        {
          distributionElement.SenderRole.Add(servicerole);
        }
        else
        {
          bool added = false;
          foreach (ValueList list in distributionElement.SenderRole)
          {
            if (list.ValueListURN == ICNETSOAConstants.ICNETServicesURI)
            {
              list.Value.Clear();
              list.Value.Add(ICNETSOAConstants.ExceptionServiceNamespace);
              added = true;
              break;
            }
          }

          if (!added)
          {
            distributionElement.SenderRole.Add(servicerole);
          }
        }

        RouterClient client = new RouterClient();
        client.ProcessDE(distributionElement);
      }
    }
  }
}
